package com.xiaomi.front.controller;

import com.xiaomi.front.service.user.UserService;
import com.xiaomi.pojo.User;
import com.xiaomi.util.ToolsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@PropertySource("classpath:config.properties")
public class UploadController {

    @Value("${upload.path}")
    private String uploadPath ;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/upload")
    @ResponseBody
    public Map upload(MultipartFile uploadFile, HttpSession session) {
        Map result = new HashMap() ;

        //先获取原文件名称
        String fileName = uploadFile.getOriginalFilename() ;

        //修改文件名 新文件名+原文件后缀 xxxx.jpg
        String fileNewName = ToolsUtil.getFileNewName(fileName);

        File upFile = new File(uploadPath, fileNewName) ;

        //文件目录是否存在
        if(!upFile.exists()) {
            upFile.mkdirs() ;
        }

        try {
            uploadFile.transferTo(upFile);
            User ifuser=new User();
            User loginUser=(User)session.getAttribute("user");
            ifuser.setImagepath(fileNewName);
            ifuser.setUid(loginUser.getUid());
            //修改头像完成
            int state=userService.Updateinfo(ifuser);
            //刷新session
            session.removeAttribute("user");
            User user=userService.DefaultLogin(loginUser.getPnumber(),loginUser.getPassword());
            session.setAttribute("user",user);

            result.put("success", true) ;
            result.put("fileName", fileNewName) ;
            result.put("state",state);
        } catch (IOException e) {
            result.put("success", false) ;
            result.put("err", "上传失败") ;
            result.put("state",0);
            e.printStackTrace();
        }


        return result ;
    }


}
